//
//  AddBankCardViewController.m
//  FactorySale
//
//  Created by 主事丫环 on 2020/1/8.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "AddBankCardViewController.h"
#import "AddBankCardTableViewCell.h"
#import "BRPickerView.h"
#import "ZzyTextField.h"
#import "BankCardTypesModel.h"

@interface AddBankCardViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *mytableView;
@property (nonatomic, strong) NSMutableArray *mydateSource;
@property (nonatomic, strong) UIView *tabFootView;
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) ZzyTextField *cardUserTF;
@property (nonatomic, strong) ZzyTextField *bankNameTF;
@property (nonatomic, strong) ZzyTextField *cardNumTF;
@property (nonatomic, strong) NSArray *cellTitArr;
@property (nonatomic, strong) NSMutableArray *bankNameArr;
@property (nonatomic, strong) NSMutableArray *bankNameIdArr;
@property (nonatomic, strong) NSString *bankTypeId;

@end

@implementation AddBankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加银行卡";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    self.view.backgroundColor = Main_BackGroundColor;
    
    NSArray *cellTitArr = @[@"持卡人", @"银行", @"卡号"];
    self.cellTitArr = cellTitArr;
    
    self.mydateSource  = [NSMutableArray arrayWithCapacity:1];
    self.bankNameArr = [NSMutableArray arrayWithCapacity:1];
    self.bankNameIdArr = [NSMutableArray arrayWithCapacity:1];
    
    [self getBankCardTypeData]; //获取银行卡种类
    
    [self createOrderDetailUI];
    // Do any additional setup after loading the view.
}

- (void)createOrderDetailUI {
    
    self.tabFootView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 56)];
    
    _mytableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight +10, KWIDTH, KHEIGHT-kNaviHeight) style:UITableViewStyleGrouped];
    _mytableView.delegate = self;
    _mytableView.dataSource = self;
    _mytableView.estimatedRowHeight = 90;
    _mytableView.rowHeight = UITableViewAutomaticDimension;
    _mytableView.tableFooterView = [UIView new];
    //[_mytableView registerClass:[AddBankCardTableViewCell class] forCellReuseIdentifier:@"AddBankCardTableViewCell"];
    _mytableView.backgroundColor = [UIColor clearColor];
    adjustInset(_mytableView);
    [_mytableView reloadData];
    _mytableView.tableFooterView = self.tabFootView;
    [self.view addSubview:_mytableView];
    
    [self showtabFootView];
}

-(void)showtabFootView {
    
    self.tabFootView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 117)];
    
    UIButton *addBankBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [addBankBut setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    addBankBut.backgroundColor = [UIColor colorWithHexString:@"#31CEA9"];
    [addBankBut setTitle:@"保存" forState:UIControlStateNormal];
    addBankBut.frame = CGRectMake(50, 64, KWIDTH-100, 44);
    addBankBut.layer.masksToBounds = YES;
    addBankBut.layer.cornerRadius = 22;
    [self.tabFootView addSubview: addBankBut];
    [addBankBut addTarget:self action:@selector(addBankButAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    _mytableView.tableFooterView = self.tabFootView;
}

//获取银行卡种类
- (void)getBankCardTypeData {
    [NetWorkTool POST:getFactoryBankTypes param:nil success:^(id dic) {
        
        self.mydateSource = [BankCardTypesModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        
        for (NSDictionary *mydic in [dic objectForKey:@"data"]) {
            [self.bankNameArr addObject:mydic[@"bank_name"]];
            [self.bankNameIdArr addObject:mydic[@"id"]];
        }
        [self.mytableView reloadData];
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}

#pragma mark - 保存
-(void)addBankButAction:(UIButton *)but{
    
    BOOL kaHaoIsTrue = [self checkBankCardNumber:self.cardNumTF.text];
    if (kaHaoIsTrue ==NO) {
        ShowToastWithText(@"输入的银行卡号不正确");
        return ;
    }
    
    if (self.cardUserTF.text.length == 0) {
        ShowToastWithText(@"请输入持卡人姓名");
        return ;
    }
    if (self.bankNameTF.text.length == 0) {
        ShowToastWithText(@"请选择银行名称");
        return ;
    }
    if (self.cardNumTF.text.length == 0) {
        ShowToastWithText(@"请输入银行卡号");
        return ;
    }
    
    //保存
    [self addBankCardData];
    KMyLog(@"您点击了 添加银行卡下面的 保存按钮");
}

//添加银行卡 数据请求
- (void)addBankCardData {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"user_name"] = [self filterSpaces:self.cardUserTF.text]; //持卡人姓名
    param[@"card_name"] = [self filterSpaces:self.bankNameTF.text]; //银行名称
    param[@"card_no"] = [self filterSpaces:self.cardNumTF.text]; //银行卡号
    param[@"bank_type_id"] = _bankTypeId;
    param[@"is_default"] = @"0"; //是否默认
    
    [NetWorkTool POST:addFactoryBankCard param:param success:^(id dic) {
        NSString *tip = dic[@"msg"];
        ShowToastWithText(tip);
        [self.navigationController popViewControllerAnimated:YES];
        
    } other:^(id dic) {
        NSString *tip = dic[@"msg"];
        ShowToastWithText(tip);
    } fail:^(NSError *error) {

    } needUser:YES];
}
// 过滤空格
- (NSString *)filterSpaces:(NSString *)text{
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"\n"withString:@""];
    return text;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellTitArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, 40)];
    headerView.backgroundColor = Main_BackGroundColor;
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, KWIDTH-40, 20)];
    titleLab.text = @"请绑定持卡人本人的银行卡";
    titleLab.textColor = K666666;
    titleLab.font = FontSize(14);
    titleLab.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:titleLab];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    static NSString *cellID = @"testCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:16.0f];
    cell.textLabel.textColor = K666666;
    NSString *title = [self.cellTitArr objectAtIndex:indexPath.row];
    
    if ([title hasPrefix:@"* "]) {
        NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc]initWithString:title];
        [textStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[[textStr string]rangeOfString:@"* "]];
        cell.textLabel.attributedText = textStr;
    } else {
        cell.textLabel.text = [self.cellTitArr objectAtIndex:indexPath.row];
    }
    
    switch (indexPath.row) {
        case 0:
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [self setupcardUserTF:cell];
        }
            break;
        case 1:
        {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            [self setupbankNameTF:cell];
        }
            break;
        case 2:
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [self setupcardNumTF:cell];
        }
            break;
            
        default:
            break;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *str = [NSString stringWithFormat:@"%@",[self.cellTitArr safeObjectAtIndex:indexPath.row]];
    KMyLog(@"dsafaf%@",str);
    if ([str isEqualToString:@"银行"]) {
        KMyLog(@"您点击了 银行 哈哈哈哈");
    }
//    NSLog(@"您点击了第 %ld 个分区 第%ld行Cell", indexPath.section, indexPath.row);
}

- (ZzyTextField *)getTextField:(UITableViewCell *)cell {
    ZzyTextField *textField = [[ZzyTextField alloc]initWithFrame:CGRectMake(80, 0, KWIDTH-100, 44)];
    textField.backgroundColor = [UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:16.0f];
    textField.textAlignment = NSTextAlignmentLeft;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.delegate = self;
    [cell.contentView addSubview:textField];
    return textField;
}

#pragma mark - 持卡人 textField
- (void)setupcardUserTF:(UITableViewCell *)cell {
    if (!_cardUserTF) {
        _cardUserTF = [self getTextField:cell];
        _cardUserTF.placeholder = @"请输入持卡人姓名";
        _cardUserTF.returnKeyType = UIReturnKeyDone;
        _cardUserTF.tag = 0;
        [_cardUserTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
}

#pragma mark - 银行 textField
- (void)setupbankNameTF:(UITableViewCell *)cell {
    if (!_bankNameTF) {
        _bankNameTF = [self getTextField:cell];
        _bankNameTF.placeholder = @"请选择银行名称";
        __weak typeof(self) weakSelf = self;
        _bankNameTF.tapAcitonBlock = ^{
            [BRStringPickerView showPickerWithTitle:@"请选择银行名称" dataSourceArr:weakSelf.bankNameArr selectIndex:0 resultBlock:^(BRResultModel *resultModel) {
                weakSelf.bankNameTF.text = resultModel.value;
                
                NSString *resultValue = resultModel.value;
                
                if ([weakSelf.bankNameArr containsObject:resultValue]) {
                    NSInteger index = [weakSelf.bankNameArr indexOfObject:resultValue];
//                    NSLog(@"下标为---%ld---",index);
                    NSString *string = [weakSelf.bankNameIdArr objectAtIndex:index];
                    KMyLog(@"根据下标取值 %@", string);
                    weakSelf.bankTypeId = string;
                }
            }];
        };
    }
}

#pragma mark - 卡号 textField
- (void)setupcardNumTF:(UITableViewCell *)cell {
    if (!_cardNumTF) {
        _cardNumTF = [self getTextField:cell];
        _cardNumTF.placeholder = @"请输入银行卡号";
        _cardNumTF.returnKeyType = UIReturnKeyDone;
        _cardNumTF.keyboardType = UIKeyboardTypeNumberPad;
        _cardNumTF.tag = 2;
    }
}

- (BOOL)checkBankCardNumber:(NSString *)cardNumber {
    int oddSum = 0;     // 奇数和
    int evenSum = 0;    // 偶数和
    int allSum = 0;     // 总和
    // 循环加和
    for (NSInteger i = 1; i <= cardNumber.length; i++) {
        NSString *theNumber = [cardNumber substringWithRange:NSMakeRange(cardNumber.length-i, 1)];
        int lastNumber = [theNumber intValue];
        if (i%2 == 0) {
            // 偶数位
            lastNumber *= 2;
            if (lastNumber > 9){
                lastNumber -=9;
            }
            evenSum += lastNumber;
        }else{
            // 奇数位
            oddSum += lastNumber;
        }
    }
    allSum = oddSum + evenSum;
    // 是否合法
    if (allSum%10 == 0){
        return YES;
    } else {
        return NO;
    }
}

- (void)textFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 5;
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength){
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

@end
